package org.blackjuly.sign.web;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.blackjuly.sign.util.StringUtil;

public class RequestManager {
	
	private HttpServletRequest request;
	
	public RequestManager(HttpServletRequest request) {
		this.request = request;
	}
	
	public int getIntParam(String name) {
		String value = request.getParameter(name);
		if (StringUtil.isNotEmpty(value)) {
			return Integer.parseInt(value);
		}
		return 0;
	}
	
	public int getIntParam(String name, int defaultValue) {
		String value = request.getParameter(name);
		if (StringUtil.isNotEmpty(value)) {
			return Integer.parseInt(value);
		}
		return defaultValue;
	}
	
	public String getParam(String name) {
		String value = request.getParameter(name);
		return value == null ? "" : value;
	}
	
	public String getParam(String name, String defaultValue) {
		String value = request.getParameter(name);
		return value == null ? defaultValue : value;
	}
	
	public <T> T getModel(Class<T> clazz) {
		T model = null;
		try {
			model = clazz.newInstance();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				String name = field.getName();
				String value = request.getParameter(name);
				if (value == null)
					continue;
				
				String methodName = "set" + StringUtil.letter(name);
				Method method = clazz.getMethod(methodName, field.getType());
				if (field.getType() == Integer.class) {
					method.invoke(model, Integer.parseInt(value));
				} else if (field.getType() == Long.class) {
					method.invoke(model, Long.parseLong(value));
				} else if (field.getType() == Float.class) {
					method.invoke(model, Float.parseFloat(value));
				} else if (field.getType() == Double.class) {
					method.invoke(model, Double.parseDouble(value));
				} else if (field.getType() == String.class) {
					method.invoke(model, value);
				} else {
					throw new RuntimeException("不支持该数据类型");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return model;
	}
	
}